﻿using NPOI.SS.UserModel;
using System;
using ZFine.Application.Gas;
using ZFine.Application.SystemManage;
using ZFine.Code;
using ZFine.Domain.Entity.Gas;
using ZFine.Domain.Entity.SystemManage;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.IO;

namespace ZFine.Web.Areas.Gas.Controllers
{
    public class FaceRecordController : ControllerBase
    {
        private FaceRecordApp faceRecordApp = new FaceRecordApp();
        private ResidentApp residentApp = new ResidentApp();

        [HttpGet]
        [HandlerAuthorize(ignore:false)]
        public override ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Form()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Details()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult FaceIndex()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult FaceDetails()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, FaceRecordEntity in_faceRecord, string StartDate, String EndDate,string txtResult)
        {
            List<FaceRecordEntity> l_faceRecord = faceRecordApp.GetList(pagination, in_faceRecord.RName, in_faceRecord.IDNumber, StartDate, EndDate, txtResult);
            var rows = from _faceRecord in l_faceRecord
                       join _resident in residentApp.GetList("")
                       on _faceRecord.IDNumber equals _resident.IDNumber into merge
                       from m in merge.DefaultIfEmpty()
                       select new
                       {
                           F_Id = _faceRecord.F_Id,
                           RName = _faceRecord.RName,
                           IDNumber = _faceRecord.IDNumber,
                           RecordTime = _faceRecord.RecordTime,
                           Satisfaction = _faceRecord.Satisfaction,
                           Result = _faceRecord.Result,
                           Telephone = m?.telephone??"",
                           Telephone2 = m?.telephone2 ?? ""
                       };
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = rows,//分页的数据
                total = pagination.total,//页数
            };
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            FaceRecordEntity data = faceRecordApp.GetForm(keyValue);
            data.FaceData = string.Format("/{0}", data.FaceData);
            return Content(data.ToJson());
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(FaceRecordEntity FaceRecordEntity, string permissionIds, string keyValue)
        {
            //只修改，不新增
            faceRecordApp.SubmitForm(FaceRecordEntity, keyValue);
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize(ignore:false)]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            faceRecordApp.Del(keyValue);
            return Success("删除成功。");
        }
        // <summary>
        /// 导出识别记录
        /// </summary>
        public FileResult ExplortFaceRecordInfo(string RName, string IDNumber, string StartDate, String EndDate, string txtResult)
        {
            List<FaceRecordEntity> l_faceRecord = faceRecordApp.GetExportList(RName, IDNumber, StartDate, EndDate, txtResult);
            foreach (var faceRecord in l_faceRecord)
            {
                ResidentEntity residentEntity = residentApp.GetFormByIDNumber(faceRecord.IDNumber);
                if (residentEntity != null)
                {
                    faceRecord.Telephone = residentEntity.telephone;
                }
            }
            var rows = (from m in l_faceRecord
                       orderby m.RecordTime descending
                       select m).ToList();
            //创建Excel文件的对象  
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet  
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("就餐记录");
            //给sheet1添加第一行的头部标题  
            NPOI.SS.UserModel.IRow row2 = sheet1.CreateRow(1);
            ICellStyle headStyle = book.CreateCellStyle();
            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font1 = book.CreateFont();
            font1.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
            font1.FontHeightInPoints = 12;
            headStyle.SetFont(font1);
            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
            headStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
            sheet1.SetColumnWidth(0, 10 * 256);
            sheet1.SetColumnWidth(1, 15 * 256);
            sheet1.SetColumnWidth(2, 25 * 256);
            sheet1.SetColumnWidth(3, 25 * 256);
            sheet1.SetColumnWidth(4, 15 * 256);
            sheet1.SetColumnWidth(5, 15 * 256);
            sheet1.SetColumnWidth(6, 20 * 256);

            IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("姓名");
            row1.CreateCell(2).SetCellValue("身份证号");
            row1.CreateCell(3).SetCellValue("就餐时间");
            row1.CreateCell(4).SetCellValue("满意度");
            row1.CreateCell(5).SetCellValue("是否刷卡");
            row1.CreateCell(6).SetCellValue("联系方式");

            for (int i = 0; i < rows.Count; i++)
            {
                IRow row = sheet1.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(Convert.ToString(i + 1));
                row.CreateCell(1).SetCellValue(rows[i].RName);
                row.CreateCell(2).SetCellValue(rows[i].IDNumber);
                row.CreateCell(3).SetCellValue(rows[i].RecordTime.ToString(PubClass.TimeFormat));
                row.CreateCell(4).SetCellValue(rows[i].Satisfaction);
                row.CreateCell(5).SetCellValue(rows[i].Result);
                row.CreateCell(6).SetCellValue(rows[i].Telephone);
            }
            string strdate = DateTime.Now.ToString("yyyyMMddHHmmss");//获取当前时间  
            // 写入到客户端   
            MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms -excel", "就餐记录" + strdate + ".xls");
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridFaceTotal(Pagination pagination, FaceRecordEntity in_faceRecord, string StartDate, String EndDate)
        {
            List<FaceRecordEntity> l_faceRecord = faceRecordApp.GetFaceTotalList(in_faceRecord.RName, in_faceRecord.IDNumber, StartDate, EndDate, ZFine.Application.Enum.Gas.FaceRecordResult.已刷卡.ToString());
            var l_faceCount = (from faceCount in l_faceRecord
                                 group faceCount by faceCount.IDNumber into s
                                 select (new { IDNumner = s.Key, count = s.Count() })).ToList();
            var _l_new_faceRecord = (from _faceRecord in l_faceRecord
                       join _faceCount in l_faceCount on _faceRecord.IDNumber equals _faceCount.IDNumner into merge
                       from m in merge.DefaultIfEmpty()
                       select new
                       {
                           RName = _faceRecord.RName,
                           IDNumber = _faceRecord.IDNumber,
                           FaceRecordCount = m?.count.ToString() ?? "0",
                       }).Distinct().ToList();
            var l_resident = residentApp.GetIQueryable().ToList();
            var rows = from _new_faceRecord in _l_new_faceRecord
                       join _resident in l_resident on _new_faceRecord.IDNumber equals _resident.IDNumber into merge
                       from m in merge.DefaultIfEmpty()
                       select new
                       {
                           RName = _new_faceRecord.RName,
                           IDNumber = _new_faceRecord.IDNumber,
                           FaceRecordCount = _new_faceRecord.FaceRecordCount,
                           Telephone = m?.telephone ?? "",
                       };
            //记录总数
            pagination.records = rows.ToArray().Length;
            //总页数
            int pageMod = pagination.records % pagination.rows;
            int pageTotal = pagination.records / pagination.rows;
            if (0 != pageMod) pageTotal = pageTotal + 1;
            //当前页的数据
            rows = rows.Skip((pagination.page - 1) * pagination.rows).Take(pagination.rows).ToList();
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = rows,//分页的数据
                total = pageTotal,//页数
            };
            return Content(data.ToJson());
        }

        // <summary>
        /// 导出识别记录
        /// </summary>
        public FileResult ExplortFaceTotalInfo(string StartDate, String EndDate, string RName, String IDNumber)
        {
            List<FaceRecordEntity> l_faceRecord = faceRecordApp.GetFaceTotalList(RName, IDNumber,StartDate, EndDate, ZFine.Application.Enum.Gas.FaceRecordResult.已刷卡.ToString()).OrderByDescending(p => p.RecordTime).ToList();
            var l_faceCount = (from faceCount in l_faceRecord
                               group faceCount by faceCount.IDNumber into s
                               select (new { IDNumner = s.Key, count = s.Count() })).ToList();
            var _l_new_faceRecord = (from _faceRecord in l_faceRecord
                        join _faceCount in l_faceCount on _faceRecord.IDNumber equals _faceCount.IDNumner into merge
                        from m in merge.DefaultIfEmpty()
                        select new
                        {
                            RName = _faceRecord.RName,
                            IDNumber = _faceRecord.IDNumber,
                            FaceRecordCount = m?.count.ToString() ?? "0",
                        }).Distinct().ToList();
            var rows = (from _new_faceRecord in _l_new_faceRecord
                       join _resident in residentApp.GetIQueryable().ToList() on _new_faceRecord.IDNumber equals _resident.IDNumber into merge
                       from m in merge.DefaultIfEmpty()
                       select new
                       {
                           RName = _new_faceRecord.RName,
                           IDNumber = _new_faceRecord.IDNumber,
                           FaceRecordCount = _new_faceRecord.FaceRecordCount,
                           Telephone = m?.telephone ?? "",
                       }).ToList();
            //创建Excel文件的对象  
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            if (string.IsNullOrEmpty(StartDate))
            {
                StartDate = "2020-01-01";
            }
            if (string.IsNullOrEmpty(EndDate))
            {
                EndDate = DateTime.Now.ToString("yyyy-MM-dd");
            }
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet(string.Format("{0}-{1}",DateTime.Parse(StartDate).ToString(PubClass.DateFormat2), DateTime.Parse(EndDate).ToString(PubClass.DateFormat2)));
            //给sheet1添加第一行的头部标题  
            NPOI.SS.UserModel.IRow row2 = sheet1.CreateRow(1);
            ICellStyle headStyle = book.CreateCellStyle();
            headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            headStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.FillPattern = FillPattern.SolidForeground;
            IFont font1 = book.CreateFont();
            font1.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
            font1.FontHeightInPoints = 12;
            headStyle.SetFont(font1);
            headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.DarkTeal.Index;
            headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
            headStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Orange.Index;
            sheet1.SetColumnWidth(0, 10 * 256);
            sheet1.SetColumnWidth(1, 15 * 256);
            sheet1.SetColumnWidth(2, 25 * 256);
            sheet1.SetColumnWidth(3, 15 * 256);
            sheet1.SetColumnWidth(4, 25 * 256);

            IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("序号");
            row1.CreateCell(1).SetCellValue("姓名");
            row1.CreateCell(2).SetCellValue("身份证号");
            row1.CreateCell(3).SetCellValue("就餐次数");
            row1.CreateCell(4).SetCellValue("联系方式");

            int faceRecordTotal = 0;
            for (int i = 0; i < rows.Count; i++)
            {
                IRow row = sheet1.CreateRow(i + 1);
                row.CreateCell(0).SetCellValue(Convert.ToString(i + 1));
                row.CreateCell(1).SetCellValue(rows[i].RName);
                row.CreateCell(2).SetCellValue(rows[i].IDNumber);
                row.CreateCell(3).SetCellValue(rows[i].FaceRecordCount);
                row.CreateCell(4).SetCellValue(rows[i].Telephone);
                faceRecordTotal += int.Parse(rows[i].FaceRecordCount);
            }
            IRow rowEnd = sheet1.CreateRow(rows.Count + 1);
            rowEnd.CreateCell(2).SetCellValue("合计：");
            rowEnd.CreateCell(3).SetCellValue(faceRecordTotal.ToString());

            string strdate = DateTime.Now.ToString("yyyyMMddHHmmss");//获取当前时间  
            // 写入到客户端   
            MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms -excel", "就餐记录" + strdate + ".xls");
        }
    }
}
